﻿using System;
using System.Threading;
using Microsoft.Ccr.Core;

namespace Test.CcrFlows
{
    static class PortExtensions
    {
        public static void Post<T>(this IPort port, T element)
        {
            ((Port<T>) port).Post(element);
        }


        public static bool WaitFor<T>(this Port<T> port, out T element)
        {
            return port.WaitFor(Timeout.Infinite, out element);
        }

        public static bool WaitFor<T>(this Port<T> port, int timeout, out T element)
        {
            T elementReceived = default(T);
            AutoResetEvent receiveFlag = new AutoResetEvent(false);

            var oneOffReceiver = port.Receive(e =>{
                                                      elementReceived = e;
                                                      receiveFlag.Set();
                                                  });
            Arbiter.Activate(
                new DispatcherQueue(),
                oneOffReceiver
                );
            bool wasElementReceived = receiveFlag.WaitOne(timeout);
            oneOffReceiver.Cleanup();

            element = elementReceived;
            return wasElementReceived;
        }
    }
}
